package net.swl.linkedvillage.database;

import android.content.Context;
import android.database.SQLException;
import android.util.Log;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
//import net.sqlcipher.database.SQLiteDatabase;
//import net.sqlcipher.database.SQLiteOpenHelper;

public class DBAdapter {

	public static final String KEY_TITLE = "title";
	public static final String KEY_BODY = "body";
	public static final String KEY_DATA = "odata";
	public static final String KEY_TYPE = "otype";
	public static final String KEY_ROWID = "_id";

	private static final String TAG = "DBAdapter";

	private static DBAdapter instance;

	private DatabaseHelper mDbHelper;
	private static SQLiteDatabase mDb;

	private static final String DATABASE_NAME = "genefighterdb";
	private static final int DATABASE_VERSION = 3;

	private Context mCtx;

	private DBAdapter(Context ctx) {
		this.mCtx = ctx;
	}
	
	public synchronized static SQLiteDatabase getmDb() {
		return mDb;
	}

	public static synchronized DBAdapter getInstance(Context ctx) {

		if (instance == null) {
			instance = new DBAdapter(ctx).open();
		}

		return instance;
	}

	/**
	 * Open the database. If it cannot be opened, try to create a new instance
	 * of the database. If it cannot be created, throw an exception to signal
	 * the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public DBAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);

		//mDb = mDbHelper.getWritableDatabase(password); SQL CIPHER
		mDb = mDbHelper.getWritableDatabase();
		

		System.gc();
		return this;
	}

	public boolean isOpen() {
		if (mDb != null)
			return mDb.isOpen();
		else
			return false;
	}

	public void rekey(String password) {
		mDb.execSQL("PRAGMA rekey = '" + password + "'");
		System.gc();
	}

	public void close() {
		mDbHelper.close();
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		
		private Context contexto;

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			this.contexto = context;

		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			SQLParser sp = new SQLParser(this.contexto, db);
			sp.parse();
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			 db.execSQL("DROP TABLE IF EXISTS player;");
			 db.execSQL("DROP TABLE IF EXISTS piece;");
			 db.execSQL("DROP TABLE IF EXISTS particle;");
			 onCreate(db);
		}
	}

}
